<template>
  <a-card>
    <!-- 搜索表单 -->
    <a-form class="smart-query-form" v-show="showSearch">
      <a-row class="smart-query-form-row">
        <a-form-item label="大本营名称" class="smart-query-form-item">
          <a-input
            v-model:value="queryParams.name"
            placeholder="请输入大本营名称"
            allow-clear
            @press-enter="handleQuery"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="大本营位置" class="smart-query-form-item">
          <a-input
            v-model:value="queryParams.weizhi"
            placeholder="请输入大本营位置"
            allow-clear
            @press-enter="handleQuery"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button-group>
            <a-button type="primary" @click="handleQuery">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form>

    <!-- 操作按钮 -->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button
          type="primary"
          @click="handleAdd"
          v-privilege="'DabenyingSys:Dabenyinginfo:add'"
        >
          <template #icon>
            <PlusOutlined />
          </template>
          新增
        </a-button>
        <a-button
          type="default"
          :disabled="single"
          @click="handleUpdate"
          v-privilege="'DabenyingSys:Dabenyinginfo:edit'"
        >
          <template #icon>
            <EditOutlined />
          </template>
          修改
        </a-button>
        <a-button
          danger
          :disabled="multiple"
          @click="handleDelete"
          v-privilege="'DabenyingSys:Dabenyinginfo:remove'"
        >
          <template #icon>
            <DeleteOutlined />
          </template>
          删除
        </a-button>
        <a-button
          @click="handleExport"
          v-privilege="'DabenyingSys:Dabenyinginfo:export'"
        >
          <template #icon>
            <DownloadOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.OFFROAD.DABENYING_INFO" :refresh="getList" />
      </div>
    </a-row>

    <!-- 表格显示 -->
    <a-table
      :loading="loading"
      :data-source="DabenyinginfoList"
      :columns="columns"
      :row-selection="rowSelection"
      :pagination="false"
      row-key="name"
      size="small"
      bordered
    >
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'photo'">
          <a-image
            v-if="record.photo"
            :src="record.photo"
            :width="50"
            :height="50"
            style="object-fit: cover"
          />
          <span v-else>-</span>
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button type="link" @click="handleUpdate(record)" v-privilege="'DabenyingSys:Dabenyinginfo:edit'">
            <template #icon>
              <EditOutlined />
            </template>
            修改
          </a-button>
          <a-button type="link" danger @click="handleDelete(record)" v-privilege="'DabenyingSys:Dabenyinginfo:remove'">
            <template #icon>
              <DeleteOutlined />
            </template>
            删除
          </a-button>
        </template>
      </template>
    </a-table>

    <!-- 分页 -->
    <div class="smart-query-table-page" v-show="total > 0">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="['10', '20', '50', '100']"
        :defaultPageSize="queryParams.pageSize"
        v-model:current="queryParams.pageNum"
        v-model:pageSize="queryParams.pageSize"
        :total="total"
        @change="getList"
        @showSizeChange="getList"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <!-- 添加或修改大本营信息对话框 -->
    <a-modal :title="title" v-model:open="open" width="500px" :mask-closable="false">
      <a-form ref="DabenyinginfoRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="大本营名称" name="name">
          <a-input v-model:value="form.name" placeholder="请输入大本营名称" />
        </a-form-item>
        <a-form-item label="大本营图片" name="photo">
          <FileUpload
            v-model:value="form.photo"
            list-type="picture-card"
            :maxUploadSize="1"
            buttonText="上传图片"
            accept="image/*"
          />
        </a-form-item>
        <a-form-item label="大本营位置" name="weizhi">
          <a-input-group compact>
            <a-input
              v-model:value="form.weizhi"
              placeholder="请选择大本营位置"
              readonly
              style="width: calc(100% - 100px)"
            />
            <a-button type="primary" @click="openMapDialog" style="width: 100px">选取位置</a-button>
          </a-input-group>
        </a-form-item>
        <a-form-item label="大本营地址" name="dizhi">
          <a-input v-model:value="form.dizhi" placeholder="请输入大本营地址" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="cancel">取 消</a-button>
        <a-button type="primary" @click="submitForm">确 定</a-button>
      </template>
    </a-modal>

    <!-- 地图选点对话框 -->
    <a-modal title="地图选点" v-model:open="mapDialogVisible" width="70%" :mask-closable="false" @cancel="closeMapDialog">
      <div id="mapContainer" style="width: 100%; height: 400px;"></div>
      <template #footer>
        <a-button @click="closeMapDialog">取消</a-button>
        <a-button type="primary" @click="confirmLocation">确定</a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, getCurrentInstance } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import {
  listDabenyinginfo,
  getDabenyinginfo,
  delDabenyinginfo,
  addDabenyinginfo,
  updateDabenyinginfo
} from "/@/api/offroad/DabenyingSys/Dabenyinginfo";
import FileUpload from "/@/components/support/file-upload/index.vue";
import TableOperator from "/@/components/support/table-operator/index.vue";
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';

const { proxy } = getCurrentInstance();

// 列表与分页
const DabenyinginfoList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const selectedRowKeys = ref([]);

// 表格列定义
const columns = ref([
  {
    title: '大本营名称',
    dataIndex: 'name',
    align: 'center',
  },
  {
    title: '大本营图片',
    dataIndex: 'photo',
    align: 'center',
    width: 120,
  },
  {
    title: '大本营位置',
    dataIndex: 'weizhi',
    align: 'center',
  },
  {
    title: '大本营地址',
    dataIndex: 'dizhi',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    width: 150,
    fixed: 'right',
  },
]);

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (selectedKeys, selectedRows) => {
    selectedRowKeys.value = selectedKeys;
    ids.value = selectedKeys;
    single.value = selectedKeys.length !== 1;
    multiple.value = selectedKeys.length === 0;
  }
};

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  photo: null,
  weizhi: null,
  dizhi: null
});

// 表单弹窗
const open = ref(false);
const title = ref('');
const form = reactive({
  oldName: '',   // 用于区分更新时的“原 name”
  name: '',
  photo: '',
  weizhi: '',
  dizhi: ''
});
const rules = reactive({
  name: [ { required: true, message: "大本营名称不能为空", trigger: "blur" } ]
});

// 地图选点
const mapDialogVisible = ref(false);
let map = null;
let marker = null;
let pickedLngLat = null;
let pickedAddress = '';

// 方法
function getList() {
  loading.value = true;
  listDabenyinginfo(queryParams).then(res => {
    DabenyinginfoList.value = res.data.list;
    total.value = res.data.total;
  }).finally(() => loading.value = false);
}

function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

function resetQuery() {
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  queryParams.name = null;
  queryParams.photo = null;
  queryParams.weizhi = null;
  queryParams.dizhi = null;
  getList();
}



function handleAdd() {
  title.value = '新增大本营';
  Object.assign(form, {
    oldName: '',
    name: '',
    photo: '',
    weizhi: '',
    dizhi: ''
  });
  open.value = true;
}


function handleUpdate(row) {
  reset();
  title.value = '修改大本营';
  // row.name 就是数据库里的主键
  getDabenyinginfo(row.name).then(res => {
    Object.assign(form, {
      oldName: row.name,    // 保存原主键
      name: row.name,
      photo: row.photo,
      weizhi: row.weizhi,
      dizhi: row.dizhi
    });
  });
  open.value = true;
}

// 表单重置
function reset() {
  Object.assign(form, {
    oldName: '',
    name: '',
    photo: '',
    weizhi: '',
    dizhi: ''
  });
  // 重置表单验证状态
  if (proxy.$refs.DabenyinginfoRef) {
    proxy.$refs.DabenyinginfoRef.resetFields();
  }
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _names = row?.name || ids.value;
  Modal.confirm({
    title: '确认删除',
    content: `是否确认删除大本营信息编号为"${_names}"的数据项？`,
    onOk() {
      return delDabenyinginfo(_names).then(() => {
        getList();
        message.success("删除成功");
      });
    }
  });
}

function handleExport() {
  // 这里需要根据实际的导出API进行调整
  console.log('导出功能需要根据实际API实现');
  message.info('导出功能需要根据实际API实现');
}

function submitForm() {
  if (proxy.$refs.DabenyinginfoRef) {
    proxy.$refs.DabenyinginfoRef.validate().then(() => {
      // oldName 为空 => 新增；否则走更新
      if (!form.oldName) {
        addDabenyinginfo({
          name: form.name,
          photo: form.photo,
          weizhi: form.weizhi,
          dizhi: form.dizhi
        }).then(() => {
          message.success('新增成功');
          open.value = false;
          getList();
        });
      } else {
        // 更新时，把 oldName 作为查询条件、新 name = form.name
        updateDabenyinginfo({
          oldName: form.oldName,
          name: form.name,
          photo: form.photo,
          weizhi: form.weizhi,
          dizhi: form.dizhi
        }).then(() => {
          message.success('修改成功');
          open.value = false;
          getList();
        });
      }
    }).catch(() => {
      console.log('表单验证失败');
    });
  }
}


function cancel() {
  open.value = false;
}

function openMapDialog() {
  mapDialogVisible.value = true;
  nextTick(() => { if (!map) initMap(); });
}

function closeMapDialog() {
  mapDialogVisible.value = false;
}

async function initMap() {
  await AMapLoader.load({ key: 'b16861868f00acd6d2cb883e30e5b598', version: '2.0', plugins: ['AMap.Geocoder'] });
  // @ts-ignore
  map = new window.AMap.Map('mapContainer', { zoom: 15, center: [116.397428, 39.90923] });
  map.on('click', async e => {
    const lnglat = e.lnglat;
    pickedLngLat = [lnglat.lng, lnglat.lat];
    if (marker) marker.setPosition(lnglat);
    // @ts-ignore
    else marker = new window.AMap.Marker({ position: lnglat, map });
    // @ts-ignore
    const geocoder = new window.AMap.Geocoder();
    const result = await geocoder.getAddress(lnglat);
    pickedAddress = result.regeocode.formattedAddress;
  });
}

function confirmLocation() {
  if (pickedLngLat) {
    form.weizhi = `${pickedLngLat[1].toFixed(6)},${pickedLngLat[0].toFixed(6)} ${pickedAddress}`;
  }
  closeMapDialog();
}

// 初始化列表
onMounted(getList);
</script>

<style scoped>
#mapContainer { border: 1px solid #ddd; border-radius: 4px; }
.mb8 { margin-bottom: 8px; }
.small-padding { padding: 4px; }
.fixed-width { width: 120px; }
.dialog-footer { text-align: right; }
</style>
